package cn.yechen.yygh.email.service.impl;

import cn.yechen.yygh.email.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author yechen
 * @create 2021-08-21 13:05
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public boolean sendCode(String phone, String code) {
        //判断手机号是否为空
        if(StringUtils.isEmpty(phone)) {
            return false;
        }

        // 准备发送邮件的参数
        String msg = "[尚医通] 您的验证码为：" + code;
        String sendTo = phone + "@163.com";

        // 发送邮件
        try {
            sendEmail(msg, sendTo);
        } catch (MailException e) {
            return false;
        }
        return true;
    }

    // 发送邮件
    private void sendEmail(String msg, String sendTo) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject("尚医通");
        // 设置邮件发送者，这个跟application.yml中设置的要一致
        message.setFrom("3011711355@qq.com");
        // 设置邮件的接受者
        message.setTo(sendTo);
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText(msg);
        // 发送邮件
        javaMailSender.send(message);
    }
}
